package com.jsmile.cloud.accountcenter.account.service;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jsmile.cloud.accountcenter.account.model.Member;
import com.jsmile.cloud.accountcenter.account.repo.MemberSearchRepository;
import com.jsmile.cloud.accountcenter.api.enums.AccountCodeEnum;
import com.jsmile.cloud.accountcenter.api.exception.AccountException;
import com.jsmile.cloud.accountcenter.api.req.account.ReqMemberQuery;
import com.jsmile.cloud.accountcenter.api.res.ResMember;
import com.jsmile.mall.api.enums.JSmileCacheEnum;
import com.jsmile.mall.api.exception.ExceptionKit;

import cn.hutool.core.bean.BeanUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@AllArgsConstructor
public class MemberApplicationService {

    private final MemberSearchRepository memberSearchRepository;

    @Cacheable(value = JSmileCacheEnum.JSmileCacheName.oneMonth, key = "'member_'+#userId")
    public ResMember getMember(long userId, long tenantId) {
        log.info("获取会员信息:{]", userId);
        Member member = memberSearchRepository.findOneByUserIdAndTenantId(userId, tenantId);
        if (null == member) {
            throw new AccountException(AccountCodeEnum.MEMBER_NOT_EXISTS);
        }
        return BeanUtil.toBean(member, ResMember.class);
    }

    public IPage<ResMember> getMemberPageList(ReqMemberQuery reqMemberQuery) {
        ExceptionKit.checkNotNull(reqMemberQuery.getCurTenantId(), "租户id不能为空!");
        log.info("会员查询:{]", reqMemberQuery);
        IPage<Member> pages = memberSearchRepository.pageQuery(reqMemberQuery);
        IPage<ResMember> res = pages.convert(x -> BeanUtil.toBean(x, ResMember.class));
        return res;
    }

}
